import asyncio
import time

from apps.database import mongo, get_ods
from apps.global_config import configs
from apps.models.QueryModel import QueryDetail, QuerySchema
from apps.scheduler.works_scheduler import run as work_run
from apps.scheduler.works_scheduler import run_dwd as work_run_dwd
from apps.scheduler.calendar_scheduler import run as calendar_run
from apps.scheduler.calendar_scheduler import run_dwd as calendar_run_dwd
from apps.scheduler.person_scheduler import run as person_run
from apps.scheduler.person_scheduler import run_dwd as person_run_dwd
from apps.scheduler.place_scheduler import run as place_run
from apps.scheduler.place_scheduler import run_dwd as place_run_dwd


async def get_task():
    qd = QueryDetail(field_name='status', field_value=0, link='and', oparation='eq')
    query = QuerySchema(
        query=[qd],
        limit=100
    )
    ods_result = await get_ods(query.get_filter(),
                               query.get_projection(),
                               query.get_sort_by(),
                               query.skip,
                               query.limit)

    qd = QueryDetail(field_name='status', field_value=1, link='and', oparation='eq')
    query = QuerySchema(
        query=[qd],
        projection=['lngid']
    )
    dwd_result = await get_ods(query.get_filter(),
                               query.get_projection(),
                               query.get_sort_by(),
                               query.skip,
                               query.limit)

    return ods_result, dwd_result


async def run_task():
    mongo.init(configs.MONGO_URI)
    count = 0
    while count < 10:
        count = count + 1
        ods_result, dwd_result = await get_task()
        if len(ods_result) > 0 or len(dwd_result) > 0:
            await work_run()
            await work_run_dwd()
            await calendar_run()
            await calendar_run_dwd()
            await person_run()
            await person_run_dwd()
            await place_run()
            await place_run_dwd()
        else:
            break


if __name__ == "__main__":
    while True:
        asyncio.run(run_task())
        print("sleep 300s")
        time.sleep(60 * 5)
